package com.common;

import android.app.Application;
import android.content.Context;
import android.os.StrictMode;

import com.lsz.deport.db.dao_utils.DaoUtils;
import com.util_code.BuildConfig;
import com.util_code.base.BaseApplication;
import com.util_code.download.DownloadConfiguration;
import com.util_code.download.DownloadManager;
import com.util_code.utils.AndroidUtils;
import com.common.dagger.component.DaggerMyAppComponent;
import com.common.dagger.component.MyAppComponent;
import com.common.dagger.module.MyAppModule;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;

public class UIApplication extends BaseApplication {

    private static MyAppComponent mMyAppComponent;
    private static RefWatcher mRefWatcher;

    @Override
    public void onCreate() {
        super.onCreate();

        setDebugMode();

        initMyAppInject(this);

        DaoUtils.init(this);

        initDownloader(this);
    }


    public void initMyAppInject(Context context) {
        mMyAppComponent = DaggerMyAppComponent.builder().
                appComponent(getAppComponent()).myAppModule(new MyAppModule()).build();
    }

    public static MyAppComponent getMyAppComponent() {
        return mMyAppComponent;
    }


    public static void setDebugMode() {
        if (BuildConfig.DEBUG) {
            mRefWatcher = LeakCanary.install((Application) AndroidUtils.getContext());

            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads()
                    .detectDiskWrites()
                    .detectNetwork()
                    .penaltyLog()
                    .build());

            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
                    .detectLeakedClosableObjects()
                    .penaltyLog()
                    .build());

        }

    }

    public static RefWatcher getRefWatcher(Context context) {
        // LeakCanary: Detect all memory leaks!
        // LeakCanary.install() returns a pre configured RefWatcher. It also
        // installs an ActivityRefWatcher that automatically detects if an activity is
        // leaking after Activity.onDestroy() has been called.
        return mRefWatcher;
    }

    private static void initDownloader(Context context) {
        DownloadConfiguration configuration = new DownloadConfiguration();
        configuration.setMaxThreadNum(6);
        DownloadManager.getInstance().init(context, configuration);
    }

}
